<template>
  <!-- 顶部导航栏的通知铃铛组件 - 微博风格 -->
  <el-popover
    v-model:visible="popoverVisible"
    placement="bottom-end"
    :width="420"
    trigger="click"
    :popper-options="{
      modifiers: [
        {
          name: 'offset',
          options: {
            offset: [0, 10]
          }
        }
      ]
    }"
    @show="handlePopoverShow"
  >
    <template #reference>
      <div class="notification-bell-wrapper">
        <el-badge
          :value="unreadCount"
          :hidden="unreadCount === 0"
          :max="99"
          :type="unreadCount > 0 ? 'danger' : 'info'"
        >
          <div class="bell-icon-wrapper">
            <el-icon
              :size="20"
              class="notification-bell"
              :class="{ 'has-unread': unreadCount > 0 }"
            >
              <Bell />
            </el-icon>
          </div>
        </el-badge>
      </div>
    </template>

    <!-- 弹出框内容 - 微博风格 -->
    <div class="weibo-notification-popover">
      <!-- 头部 -->
      <div class="popover-header">
        <div class="header-content">
          <span class="title">通知</span>
          <span v-if="unreadCount > 0" class="unread-badge"
            >{{ unreadCount }}条未读</span
          >
        </div>
        <el-button
          link
          size="small"
          :disabled="unreadCount === 0"
          @click="handleMarkAllAsRead"
        >
          全部已读
        </el-button>
      </div>

      <!-- 通知列表 -->
      <div v-loading="loading" class="notification-list">
        <div
          v-for="notification in latestNotifications"
          :key="notification.id"
          class="notification-item"
          :class="{ 'is-unread': !notification.isRead }"
          @click="handleNotificationClick(notification)"
        >
          <div class="item-avatar">
            <el-avatar
              :src="formatAvatarUrl(notification.sender?.avatar)"
              :size="40"
            >
              {{ notification.sender?.nickName?.charAt(0) }}
            </el-avatar>
          </div>

          <div class="item-content">
            <div class="content-header">
              <span class="sender-name">{{
                notification.sender?.nickName
              }}</span>
              <span class="action-text">{{ notification.actionText }}</span>
            </div>

            <!-- 显示文章标题或评论内容 -->
            <div v-if="notification.articleInfo" class="content-target">
              {{ notification.articleInfo.title }}
            </div>
            <div v-else-if="notification.commentDetail" class="content-target">
              {{ notification.commentDetail.content }}
            </div>

            <div class="content-footer">
              <span class="time-text">{{
                formatTime(notification.createTime)
              }}</span>
            </div>
          </div>

          <div class="item-indicator">
            <div v-if="!notification.isRead" class="unread-dot" />
          </div>
        </div>

        <!-- 空状态 -->
        <div
          v-if="!loading && latestNotifications.length === 0"
          class="empty-state"
        >
          <el-icon :size="48" class="empty-icon"><BellFilled /></el-icon>
          <p class="empty-text">暂无通知</p>
        </div>
      </div>

      <!-- 底部 -->
      <div class="popover-footer">
        <el-button link class="view-all-btn" @click="goToNotificationCenter">
          查看全部通知
          <el-icon class="arrow-icon"><ArrowRight /></el-icon>
        </el-button>
      </div>
    </div>
  </el-popover>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Bell, BellFilled, ArrowRight } from "@element-plus/icons-vue";
import {
  markAllNotificationsAsReadApi,
  markNotificationAsReadApi,
  type NotificationDetail
} from "@/api/notification";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import { notificationService } from "@/services/notificationService";

const router = useRouter();
const loading = ref(false);
const popoverVisible = ref(false);

// 使用单例服务的响应式数据
const statsRef = notificationService.getStatsRef();
const latestNotifications = notificationService.getLatestNotificationsRef();

// 计算未读数量
const unreadCount = computed(() => {
  return statsRef.value?.totalUnreadCount || 0;
});

// 格式化头像URL
const formatAvatarUrl = (url: string): string => {
  if (!url) return "";

  // 如果已经是完整URL，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // 如果是相对路径，添加基础URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};

// 加载最新通知
const loadLatestNotifications = async () => {
  loading.value = true;
  try {
    await notificationService.loadLatestNotifications(10);
  } finally {
    loading.value = false;
  }
};

// 弹出框显示时刷新数据
const handlePopoverShow = () => {
  loadLatestNotifications();
};

// 点击通知项
const handleNotificationClick = async (notification: NotificationDetail) => {
  // 标记为已读
  if (!notification.isRead) {
    try {
      await markNotificationAsReadApi(notification.id);
      notification.isRead = 1;
      notificationService.decreaseUnreadCount(1);
    } catch (error) {
      console.error("标记已读失败", error);
    }
  }

  // 关闭弹出框
  popoverVisible.value = false;

  // 跳转到目标页面
  if (notification.target?.url) {
    router.push(notification.target.url);
  }
};

// 全部标记为已读
const handleMarkAllAsRead = async () => {
  try {
    const response = await markAllNotificationsAsReadApi();
    if (response.code === 200) {
      ElMessage.success("已全部标记为已读");
      latestNotifications.value.forEach(n => (n.isRead = 1));
      notificationService.clearUnreadCount();
    }
  } catch (error) {
    ElMessage.error("操作失败");
    console.error(error);
  }
};

// 跳转到通知中心
const goToNotificationCenter = () => {
  // 关闭弹出框
  popoverVisible.value = false;
  // 跳转到消息中心（添加 from=notification 参数，默认显示系统公告标签）
  router.push("/user/messages?from=notification");
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return "";
  try {
    return formatDistanceToNow(new Date(time), {
      addSuffix: true,
      locale: zhCN
    });
  } catch (error) {
    return time;
  }
};

// 初始化
onMounted(() => {
  // 🔑 优化: 不再主动调用 loadStats()，依赖 App.vue 的统一初始化
  // 通过单例服务的 statsRef 响应式数据自动更新界面
  console.log("🔔 NotificationBell 组件已加载，使用单例服务的统计数据");
});

// 组件卸载时清理
onUnmounted(() => {
  // 单例服务会统一管理,这里不需要清理
});

// 暴露刷新方法供外部调用
defineExpose({
  refresh: () => {
    loadLatestNotifications();
  }
});
</script>

<style scoped lang="scss">
// 微博风格的通知铃铛组件
.notification-bell-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px 10px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s ease;

  &:hover {
    background: rgb(255 255 255 / 15%);

    .bell-icon-wrapper {
      transform: scale(1.1);
    }
  }

  .bell-icon-wrapper {
    transition: transform 0.3s ease;

    .notification-bell {
      color: rgb(255 255 255 / 90%);
      cursor: pointer;
      transition: all 0.3s;

      &:hover,
      &.has-unread {
        color: #ff8200;
      }
    }
  }

  :deep(.el-badge__content) {
    height: 18px;
    padding: 0 5px;
    font-size: 11px;
    line-height: 14px;
    border: 2px solid #fff;
  }
}

// 微博风格的弹出框
.weibo-notification-popover {
  .popover-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px 20px;
    background: linear-gradient(180deg, #fff 0%, #fafafa 100%);
    border-bottom: 1px solid #f0f0f0;

    .header-content {
      display: flex;
      gap: 10px;
      align-items: center;

      .title {
        font-size: 17px;
        font-weight: 600;
        color: #262626;
      }

      .unread-badge {
        padding: 2px 8px;
        font-size: 12px;
        font-weight: 500;
        color: #fff;
        background: #ff8200;
        border-radius: 10px;
      }
    }

    .el-button {
      font-size: 13px;
      color: #ff8200;

      &:hover:not(:disabled) {
        color: #f60;
      }

      &:disabled {
        color: #c0c0c0;
      }
    }
  }

  .notification-list {
    max-height: 450px;
    overflow-y: auto;

    // 自定义滚动条
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background: #dcdcdc;
      border-radius: 3px;

      &:hover {
        background: #bbb;
      }
    }
  }

  .notification-item {
    position: relative;
    display: flex;
    align-items: flex-start;
    padding: 14px 20px;
    cursor: pointer;
    border-bottom: 1px solid #f5f5f5;
    transition: all 0.2s ease;

    &:hover {
      background: #fafafa;
    }

    &:last-child {
      border-bottom: none;
    }

    &.is-unread {
      background: #fff9f0;

      &:hover {
        background: #fff5e6;
      }
    }

    .item-avatar {
      flex-shrink: 0;
      margin-right: 12px;

      .el-avatar {
        border: 2px solid #f0f0f0;
      }
    }

    .item-content {
      flex: 1;
      min-width: 0;

      .content-header {
        margin-bottom: 6px;
        line-height: 1.5;

        .sender-name {
          margin-right: 4px;
          font-size: 14px;
          font-weight: 600;
          color: #262626;
        }

        .action-text {
          font-size: 14px;
          color: #595959;
        }
      }

      .content-target {
        margin-bottom: 6px;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 13px;
        line-height: 1.4;
        color: #1890ff;
        white-space: nowrap;
      }

      .content-footer {
        .time-text {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .item-indicator {
      display: flex;
      flex-shrink: 0;
      align-items: center;
      padding-left: 8px;

      .unread-dot {
        width: 8px;
        height: 8px;
        background: #ff8200;
        border-radius: 50%;
      }
    }
  }

  // 空状态
  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;

    .empty-icon {
      margin-bottom: 12px;
      color: #d9d9d9;
    }

    .empty-text {
      margin: 0;
      font-size: 14px;
      color: #999;
    }
  }

  .popover-footer {
    padding: 12px 20px;
    text-align: center;
    background: #fafafa;
    border-top: 1px solid #f0f0f0;

    .view-all-btn {
      display: flex;
      gap: 4px;
      align-items: center;
      justify-content: center;
      width: 100%;
      font-size: 14px;
      font-weight: 500;
      color: #ff8200;

      &:hover {
        color: #f60;
      }

      .arrow-icon {
        transition: transform 0.3s ease;
      }

      &:hover .arrow-icon {
        transform: translateX(3px);
      }
    }
  }
}
</style>
